//
//  MessageModel.m
//  huashiedu
//
//  Created by oceans on 2018/9/9.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "MessageModel.h"
#import "HttpRequest.h"

@implementation MessageModel

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        __id = [[dic objectForKey:@"id"] intValue];
        _name = [dic objectForKey:@"name"];
        _logo = [dic objectForKey:@"logo"];
        _nums = [[dic objectForKey:@"nums"] intValue];
        [self loadLastMessage];
    }
    return self;
}

- (void)loadLastMessage {
    
    RCConversation *conversation = [[RCIMClient sharedRCIMClient] getConversation:ConversationType_GROUP targetId:[NSString stringWithFormat:@"%d", __id]];
    NSString *draft = [conversation draft];
    if (draft) {
        NSData *draftData = [draft dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:draftData options:NSJSONReadingAllowFragments error:nil];
        self.draftString = [dic objectForKey:@"draftContent"];
    }
    NSInteger lid = conversation.lastestMessageId;
    
    if (_message && _message.messageId == lid) {
        return;
    }
    RCMessage *message = [[RCIMClient sharedRCIMClient] getMessage:lid];
    
    if (message == nil) {
        return;
    }
    
    if (message.content.senderUserInfo == nil || message.content.senderUserInfo.userId == nil) {
        __weak typeof(self) weakself = self;
        [HttpRequest getURL:[NSString stringWithFormat:kget_ry_userinfo, message.senderUserId] paras:nil showProgress:NO successful:^(id  _Nullable result) {
            
            NSDictionary *dic = result[@"data"];
            RCUserInfo *info = [[RCUserInfo alloc] initWithUserId:message.senderUserId name:dic[@"nickname"] portrait:dic[@"avatar"]];
            weakself.message.content.senderUserInfo = info;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMessageList" object:nil];
        } failed:nil];
    }
    
    if (message) {
        self.message = message;
    }
}

@end
